package com.facebook.keyframes.sample.slice;

import com.facebook.keyframes.KeyframesDrawable;
import com.facebook.keyframes.KeyframesDrawableBuilder;
import com.facebook.keyframes.deserializers.KFImageDeserializer;
import com.facebook.keyframes.model.KFImage;
import com.facebook.keyframes.sample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Image;
import ohos.agp.components.Slider;

import java.io.IOException;
import java.io.InputStream;

public class MainAbilitySlice extends AbilitySlice {
    private static final String TAG = "KeyframesSample";
    private static final int TEST_CANVAS_SIZE_PX = 500;
    private KeyframesDrawable mKeyFramesDrawable;
    private boolean mPaused;
    private Button mTogglePauseButton, mStartButton;
    private Image imageView;
    private Slider mSeekBar;
    private boolean mDraggingSeekBar;
    private KFImage mKfImage;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mTogglePauseButton = (Button) findComponentById(ResourceTable.Id_toggle_pause_button);
        mStartButton = (Button) findComponentById(ResourceTable.Id_start_button);
        mSeekBar = (Slider) findComponentById(ResourceTable.Id_slider);
        imageView = (Image) findComponentById(ResourceTable.Id_sample_image_view);
        mStartButton.setClickedListener(component -> startAnimation());
        mTogglePauseButton.setClickedListener(component -> {
                    if (mKeyFramesDrawable == null) {
                        return;
                    }
                    if (mPaused) {
                        resumeAnimation();
                    } else {
                        pauseAnimation();
                    }
                }
        );
        initSeekBar();
        setKFImage(getSampleImage());
    }

    private void initSeekBar() {
        mSeekBar.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean b) {
                if (mDraggingSeekBar) {
                    mKeyFramesDrawable.seekToProgress((float) progress / 100);
                }
            }

            @Override
            public void onTouchStart(Slider slider) {
                mDraggingSeekBar = true;
                mKeyFramesDrawable.setAnimationListener(new KeyframesDrawable.OnAnimationEnd() {
                    @Override
                    public void onAnimationEnd() {
                        stopAnimation(true);
                    }
                });
            }

            @Override
            public void onTouchEnd(Slider slider) {
                mDraggingSeekBar = false;
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private KFImage getSampleImage() {
        InputStream stream = null;
        try {
            stream = getResourceManager().getRawFileEntry("resources/rawfile/sample_file.json").openRawFile();
            KFImage sampleImage = KFImageDeserializer.deserialize(stream);
            return sampleImage;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException ignored) {
                }
            }
        }
        return null;
    }

    private void setKFImage(KFImage kfImage) {
        clearImage();
        mKfImage = kfImage;
        mKeyFramesDrawable = new KeyframesDrawableBuilder()
                .withImage(mKfImage)
                .withMaxFrameRate(60)
                .withExperimentalFeatures()
                .withBitmaps()
                .build();
        startAnimation();

        mKeyFramesDrawable.setCallback(element -> {
            imageView.invalidate();
            mKeyFramesDrawable.setBounds(0,0,imageView.getWidth(),imageView.getHeight());
        });
        imageView.addDrawTask((component, canvas) -> mKeyFramesDrawable.drawToCanvas(canvas));
    }

    private void startAnimation() {
        mSeekBar.setProgressValue(0);
        mKeyFramesDrawable.startAnimation();
        mTogglePauseButton.setText("Pause");
        mTogglePauseButton.setEnabled(true);
        mPaused = false;
    }

    private void stopAnimation() {
        stopAnimation(false);
    }

    private void resumeAnimation() {
        mKeyFramesDrawable.resumeAnimation();
        mTogglePauseButton.setText("Pause");
        mPaused = false;
    }

    private void pauseAnimation() {
        mKeyFramesDrawable.pauseAnimation();
        mTogglePauseButton.setText("Resume");
        mPaused = true;
    }

    private void stopAnimation(boolean alreadyStopped) {
        if (!alreadyStopped) {
            mKeyFramesDrawable.stopAnimation();
        }
        mTogglePauseButton.setText("Pause");
        mTogglePauseButton.setEnabled(false);
        mPaused = true;
    }

    private void clearImage() {
        if (mKeyFramesDrawable == null) {
            return;
        }
        mKeyFramesDrawable.stopAnimation();
        mKeyFramesDrawable = null;
    }

}
